const {
    createCanvas,
    loadImage
} = require('canvas');
const fs = require('fs');
const path = require('path');

// 一维数据集
let data = JSON.parse(fs.readFileSync(path.join(__dirname, './img_data.json')).toString())

// 创建一个28x28的画布
const canvas = createCanvas(280, 280);
const ctx = canvas.getContext('2d');

// 设置画布背景为白色
ctx.fillStyle = '#ffffff';
ctx.fillRect(0, 0, canvas.width, canvas.height);

// 绘制数据集
const pixelSize = 10; // 每个像素的大小
for (let i = 0; i < data.length; i++) {
    const x = i % 28;
    const y = Math.floor(i / 28);
    const part = decimalToHex(-(data[i]-255))
    // const color = Math.round(data[i] / 255) === 1 ? '#000000' : '#ffffff';
    const color = `#${part}${part}${part}`
    ctx.fillStyle = color;
    ctx.fillRect(x * pixelSize, y * pixelSize, pixelSize, pixelSize);
}

// 将画布保存为图片
const buffer = canvas.toBuffer('image/png');
require('fs').writeFileSync('output.png', buffer);


function decimalToHex(decimal) {
    const hex = decimal.toString(16);
    return hex.length === 1 ? "0" + hex : hex;
}

// for (var i = 0; i <= 255; i++) {
//     var hex = rgbToHex(i, i, i);
//     console.log(hex);
// }